# -*- coding: utf-8 -*-
# =============================================================================
#     FileName: logger_demo.py
#         Desc: 演示使用Logging模块
#       Author: GGA
#        Email:
#     HomePage:
#      Version: 1.0.1
#   LastChange: 2020-12-20
#      History:
# =============================================================================

import os
import sys
import logging
import logging.handlers
from utils.common_config import CommonConfig


class LoggerHelper(object):
    @classmethod
    def init_logger(cls, logger_name="", logger_level=logging.INFO, logger_dir=None):
        my_logger = logging.getLogger(logger_name)
        if logger_name is None:
            logger_name = ""
        if logger_name != "":
            logger_file_name = logger_name + ".log"
        else:
            logger_file_name = "default.log"
        if logger_dir is None:
            working_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
            logger_dir = os.path.join(working_dir, "logs")
        if not os.path.exists(logger_dir):
            os.makedirs(logger_dir)
        log_file_path = os.path.join(logger_dir, logger_file_name)
        my_logger.setLevel(level=logging.DEBUG)
        logger_format = logging.Formatter("[%(asctime)s]-[%(levelname)s]: %(message)s")  # output format
        sh = logging.StreamHandler(stream=sys.stdout)  # output to standard output
        sh.setFormatter(logger_format)
        sh.setLevel(logger_level)
        my_logger.addHandler(sh)
        fh = logging.handlers.RotatingFileHandler(log_file_path, maxBytes=10 * 1024 * 1024, backupCount=5)
        fh.setFormatter(logger_format)
        fh.setLevel(logger_level)
        my_logger.addHandler(fh)


def logger_demo():
    app_name = "app"
    working_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    logger_dir = os.path.join(working_dir, "logs")
    LoggerHelper.init_logger(logger_name=app_name, logger_level=logging.DEBUG, logger_dir=logger_dir)
    logger = logging.getLogger(name=app_name)
    logger.debug("this is default debug")
    logger.info("this is default info")


if __name__ == '__main__':
    logger_demo()
